const { createResult, editResultSv, getResultListByQuestionId, getResultListByUserId, destroyResultByResultId } = require('../service/result.service')
const { getUserinfo } = require('../service/user.service')
const { serverError, noAccess } = require('../constants/error.type')
const { upgradeQuestionWeight } = require('../service/question.service')

const reply = async (ctx, next) => {
  const { questionId, content } = ctx.request.body
  const { id } = ctx.state.userinfo
  try {
    await createResult({ userId: id, questionId, content: typeof content === 'string' ? content : JSON.stringify(content) })
    ctx.body = {
      code: 0,
      message: '回复成功',
    }
  } catch (err) {
    console.error('[reply error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

const editResult = async (ctx, next) => {
  const { resultId, content } = ctx.request.body
  try {
    await editResultSv({ resultId, content: typeof content === 'string' ? content : JSON.stringify(content) })
    ctx.body = {
      code: 0,
      message: '编辑成功',
    }
  } catch (err) {
    console.error('[reply error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

const getResultsByUserId = async (ctx, next) => {
  const { id } = ctx.state.userinfo
  try {
    const resultList = await getResultListByUserId(id)
    resultList.forEach(result => {
      result.set('content', JSON.parse(result.get('content') || '{}'))
    })
    ctx.body = {
      code: 0,
      message: '获取成功',
      data: resultList
    }
  } catch (err) {
    console.error('[getResultsByUserId error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

const getResultsByQuestionId = async (ctx, next) => {
  const { questionId } = ctx.request.query

  try {
    // 获取问题的答案，则将问题权重加一
    await upgradeQuestionWeight(questionId)
    const resultList = await getResultListByQuestionId(questionId)
    for (let i = 0; i < resultList.length; i++) {
      const result = resultList[i]
      const { username } = await getUserinfo({ userId: result.answerer })
      result.setDataValue('username', username)
      result.set('content', JSON.parse(result.get('content') || '{}'))
    }
    ctx.body = {
      code: 0,
      message: '获取成功',
      data: resultList
    }
  } catch (err) {
    console.error('[getResultsByQuestionId error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

const deleteResultByResultId = async (ctx, next) => {
  const { resultId } = ctx.request.body
  const { isAdmin } = ctx.state.userinfo

  try {
    if (isAdmin) {
      await destroyResultByResultId(resultId)
      ctx.body = {
        code: 0,
        message: '删除成功'
      }
    } else {
      return ctx.app.emit('error', noAccess, ctx)
    }
  } catch (err) {
    console.error('[deleteQuestionByQuestionId error]', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

module.exports = {
  reply,
  getResultsByUserId,
  editResult,
  getResultsByQuestionId,
  deleteResultByResultId,
}
